const express = require("express");
const router = express.Router();
const path = require("path");
const utility = require("utility");
const db = require(path.join(__dirname, "../utile/db"));
const jsonwebtoken = require("jsonwebtoken");
// 注册接口
router.post("/reguser", async (req, res) => {
  console.log(req.body);
  req.body.password = utility.md5(req.body.password);
  // 使用封装好的db模块往数据库中添加注册的数据，主要使用了promise对象，来处理异步请求
  let r = await db("insert into userinfo set ?", req.body);
  if (r && r.affectedRows > 0) {
    res.send({
      status: 0,
      msg: "注册成功",
    });
  } else {
    res.send({
      status: 1,
      msg: "注册失败",
    });
  }
});
// 注册接口
router.post("/login", async (req, res) => {
  let username = req.body.username;
  let password = utility.md5(req.body.password);
  console.log(password, username);

  let r = await db("select * from userinfo where username= ? and password= ?", [
    username,
    password,
  ]);
  console.log(r);

  if (r && r.length > 0) {
    res.send({
      status: 0,
      msg: "登陆成功",
      token:
        "Bear" +
        jsonwebtoken.sign(
          {
            username: req.body.username,
            id: r[0].id,
          },
          "bigevent",
          { expiresIn: "2 days" }
        ),
    });
  } else {
    res.send({
      status: 1,
      msg: "登陆失败",
    });
  }
});
module.exports = router;
